package com.htudata.core.util;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class CustomX509TrustManager implements X509TrustManager {
  private static SSLContext sslcontext = null;
  
  private static HostnameVerifier ignoreHostnameVerifier = null;
  
  public void checkClientTrusted(X509Certificate[] certificates, String authType) throws CertificateException {}
  
  public void checkServerTrusted(X509Certificate[] ax509certificate, String s) throws CertificateException {}
  
  public X509Certificate[] getAcceptedIssuers() {
    return null;
  }
  
  public static void init() throws NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    if (sslcontext != null && ignoreHostnameVerifier != null)
      return; 
    sslcontext = SSLContext.getInstance("SSL", "SunJSSE");
    sslcontext.init(null, new TrustManager[] { new CustomX509TrustManager() }, new SecureRandom());
    ignoreHostnameVerifier = new HostnameVerifier() {
        public boolean verify(String s, SSLSession sslsession) {
          System.out.println("WARNING: Hostname is not matched for cert.");
          return true;
        }
      };
    HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
    HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
  }
}
